<script setup lang='ts'>
import type { IAdd, IEdit, IList } from '@fl/api/anjutong/model/apply-model'
import type { VxeGridInstance, VxeGridProps, VxePagerEvents } from 'vxe-table'

import { formatTime } from '@/pages/integral/helper'
import { applpyAdd, applyDetail, applyEdit, applyList, applyProduct, getLabelValue } from '@fl/api/anjutong/index'

import EditForm from './edit-form.vue'
import { formTypeEunm } from './index'

type RowVO = {
    applicantName: string
    applicantPhone: string
    applicationNumber: string
    catName: string
    createTime: string
    financialName: string
    message: string
    productName: string
}

const state = ref({
    catId: '',
    date: '',
    financialId: '',
})

const form = ref({
    applicantName: '',
    applicantPhone: '',
    creditLimit: 0,
    financialCode: '',
    financialId: '',
    id: '',
    interestRate: 0,
    message: '',
    operatorName: '',
    operatorPhone: '',
    productId: '',
    remark: '',
    status: null,
    step: [],
    type: null,
})
const submitLoading = ref(false)
const columns = [
    {
        colProps: {
            span: 6,
        },
        label: '产品分类',
        options: async () => {
            const data = await getLabelValue(1)
            return data ?? []
        },
        prop: 'catId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '金融机构',
        options: async () => {
            const data = await getLabelValue(2)
            return data ?? []
        },
        prop: 'financialId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束时间',
            format: 'YYYY-MM-DD',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
        },
        label: '发布时间',
        prop: 'date',
        valueType: 'date-picker',
    },

]
const applyProductList = ref([])
const centerDialogVisible = ref(false)
const formType = ref('')
const dialogTitle = computed(() => {
    return `${formType.value}申请单`
})
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const xGrid = ref<VxeGridInstance<RowVO>>()
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { title: '序号', type: 'seq', width: 50 },
        { field: 'applicationNumber', title: '申请单编号' },
        { field: 'productName', title: '产品名称' },
        { field: 'applicantName', title: '登记人姓名' },
        { field: 'applicantPhone', title: '手机号' },
        { field: 'catName', title: '产品分类' },
        { field: 'financialName', title: '金融机构名称' },
        { field: 'createTime', title: '申请时间' },
        { field: 'message', title: '办理结果' },
        { slots: { default: 'operate' }, title: '操作', width: 200 },

    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 380,
    keepSource: true,
    loading: false,
    showOverflow: true,
})
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}
watch(() => form.value.productId, (nval) => {
    // console.log('🚀 ~ watch ~ nval:', nval, applyProductList.value)
    const params: any = applyProductList.value.find((item: any) => item.id === nval)
    // console.log(params)
    form.value.type = params?.bizType ?? null
    form.value.financialId = params?.financialId ?? null
    form.value.financialCode = params?.financialCode ?? ''
}, { deep: true })
async function findList() {
    gridOptions.loading = true
    try {
        const params: IList = {
            catId: state.value.catId,
            endTime: formatTime(state.value.date?.[1], 'YYYY-MM-DD 23:59:59'),
            financialId: state.value.financialId,
            page: tablePage.currentPage,
            size: tablePage.pageSize,
            sort: 'create_time,desc',
            startTime: formatTime(state.value.date?.[0], 'YYYY-MM-DD 00:00:00'),
        }
        const data = await applyList(params)
        gridOptions.loading = false
        gridOptions.data = data.records
        tablePage.total = data.total
    }
    catch (error) {
        gridOptions.loading = false
    }
}
findList()
function reset() {
    state.value = {
        catId: '',
        date: '',
        financialId: '',
    }
    findList()
}
function resetFormParams() {
    submitLoading.value = false
    form.value = {
        applicantName: '',
        applicantPhone: '',
        creditLimit: 0,
        financialCode: '',
        financialId: '',
        id: '',
        interestRate: 0,
        message: '',
        operatorName: '',
        operatorPhone: '',
        productId: '',
        remark: '',
        status: null,
        step: [],
        type: null,
    }
}
async function showForm(type: string, row?: any) {
    formType.value = type
    if (formType.value === formTypeEunm.detail || formType.value === formTypeEunm.handle) {
        try {
            const data = await applyDetail(row.id)
            form.value = {
                applicantName: data?.applicantName,
                applicantPhone: data?.applicantPhone,
                creditLimit: data?.creditLimit ?? 0,
                financialCode: '',
                financialId: '',
                id: data?.id,
                interestRate: data?.interestRate ?? 0,
                message: data?.message,
                operatorName: data?.operatorName,
                operatorPhone: data?.operatorPhone,
                productId: data?.productId,
                remark: data?.remark,
                status: data?.status ?? null,
                step: data?.step ?? [],
                type: null,
            }
        }
        catch (error) {
        }
    }

    centerDialogVisible.value = true
}
function search() {
    tablePage.currentPage = 1
    findList()
}
async function getApplyProduct() {
    try {
        const data = await applyProduct()
        console.log('🚀 ~ getApplyProduct ~ data:', data)
        applyProductList.value = data ?? []
    }
    catch (error) {

    }
}
getApplyProduct()

function formSubmit() {
    if (formType.value === formTypeEunm.add)
        addData()
    if (formType.value === formTypeEunm.handle)
        editData()
}

async function addData() {
    submitLoading.value = true
    try {
        const options: IAdd = {
            applicantName: form.value.applicantName,
            applicantPhone: form.value.applicantPhone,
            creditLimit: form.value.creditLimit ?? 0,
            financialId: form.value.financialId,
            interestRate: form.value.interestRate ?? 0,
            isDeleted: 0,
            message: form.value.message,
            operatorName: form.value.operatorName,
            operatorPhone: form.value.operatorPhone,
            productId: form.value.productId,
            remark: form.value.remark,
            status: form.value.status ?? 0,
        }
        const data = await applpyAdd(options)
        if (data === 1)
            ElMessage.success('添加成功')
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
async function editData() {
    submitLoading.value = true
    try {
        const options: IEdit = {
            applicantName: form.value.applicantName,
            applicantPhone: form.value.applicantPhone,
            creditLimit: form.value.creditLimit ?? 0,
            financialId: form.value.financialId,
            id: form.value.id,
            interestRate: form.value.interestRate ?? 0,
            isDeleted: 0,
            message: form.value.message,
            operatorName: form.value.operatorName,
            operatorPhone: form.value.operatorPhone,
            productId: form.value.productId,
            remark: form.value.remark,
            status: form.value.status ?? 0,
        }
        const data = await applyEdit(options)
        if (data === 1)
            ElMessage.success('修改成功')
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
</script>

<template>
    <div class="mb-20 flex bg-white p-30">
        <div class="flex-1 pr-24">
            <PlusForm v-model="state"
                      :columns="columns"
                      :row-props="{ gutter: 20 }"
                      label-width=""
                      :has-footer="false"
            />
        </div>

        <div class="">
            <ElButton type="primary"
                      @click="search"
            >
                搜索
            </ElButton>

            <ElButton @click="reset">
                重置
            </ElButton>
        </div>
    </div>

    <div class="bg-white p-30">
        <div class="mb-20">
            <ElButton type="primary"
                      @click="showForm(formTypeEunm.add)"
            >
                {{ formTypeEunm.add }}
            </ElButton>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
        >
            <template #operate="{ row }">
                <ElButton @click="showForm(formTypeEunm.detail, row)">
                    {{ formTypeEunm.detail }}
                </ElButton>

                <ElButton @click="showForm(formTypeEunm.handle, row)">
                    {{ formTypeEunm.handle }}
                </ElButton>
            </template>

            <template #pager>
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           background
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>

    <el-dialog v-model="centerDialogVisible"
               :title="dialogTitle"
               width="950"

               destroy-on-close
               align-center
               :close-on-click-modal="false"
               @close="resetFormParams"
    >
        <div class="max-h-750 of-x-hidden of-y-auto pb-10">
            <EditForm :applyproductlist="applyProductList"
                      :form="form"
                      :loading="submitLoading"
                      :type="formType"
                      @close="centerDialogVisible = false"
                      @submit="formSubmit"
            />
        </div>
    </el-dialog>
</template>
